package com.hd.trans.share;

import android.text.TextUtils;

import com.hd.trans.network.HeaderInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class RetrofitUtil {
    /**
     *
     * @param h5HeadData        头部数据
     * @param connectTimeOut    连接超时时间
     * @param readTimeOut       读超时时间
     * @return
     */
    private static OkHttpClient getUnsafeOkHttpClient(String h5HeadData,Long connectTimeOut,Long readTimeOut){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return builder.connectTimeout(connectTimeOut, TimeUnit.SECONDS).readTimeout(readTimeOut, TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                .addInterceptor(new PostInterceptor())
                .addInterceptor(new HeaderInterceptor(true))
                .addInterceptor(chain -> {
                    Request.Builder builder1 = chain.request().newBuilder();
                    if(!TextUtils.isEmpty(h5HeadData)){
                        builder1.addHeader("ab_test_type_data", h5HeadData);
                    }
                    Request request = builder1.build();
                    return chain.proceed(request);
                })
                .addInterceptor(chain -> {
                    //存入Session
                    Response response = chain.proceed(chain.request());
                    return response;
                })
                .build();
    }

    public static Retrofit initRetrofit(String url,String h5HeadData,Long connectTimeOut,Long readTimeOut){
        OkHttpClient okHttpClient = getUnsafeOkHttpClient(h5HeadData, connectTimeOut, readTimeOut);
        return new Retrofit.Builder().client(okHttpClient)
                .baseUrl(url)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create()).build();
    }

    public static Retrofit initRetrofit(String url){
        return initRetrofit(url,null,20l,20l);
    }
}
